from django.shortcuts import render
from django.views import View
from .models import BookInfo
from django import http
import json
# Create your views here.

class BookView(View):

    def get(self,request):

        books = BookInfo.objects.all()

        return render(request, 'index.html',context={'book_list':books})

    # 增添图书
    def post(self,request):

        # 获取输入的图书
        add_book = request.POST
        try:
            # 插入数据库
            book = BookInfo(
                btitle = add_book.get('name'),
                bauthor = add_book.get('author'),
                bperson = add_book.get('hero'),
                bpub_date = add_book.get('time'),
                bread = add_book.get('read'),
                bcomment = add_book.get('comment')
            )
            book.save()
            # 返回插入结果
            return http.JsonResponse({'data':'添加成功'})
        except Exception as e:
            print(e)
            return http.JsonResponse({'data':'添加失败'})

    # 删除图书
    def delete(self,request):
        delete_book = json.loads(request.body.decode())

        try:
            book = BookInfo.objects.get(id=delete_book['id'])
            book.delete()
            return http.JsonResponse({'data':'删除成功'})
        except Exception as e:
            print(e)
            return http.JsonResponse({'data':'删除失败'})

    # 修改图书
    def put(self,request):

        updata_book = json.loads(request.body.decode())

        try:
            book = BookInfo.objects.get(id=updata_book['id'])

            book.btitle = updata_book.get('name')
            book.bauthor = updata_book.get('author')
            book.bperson = updata_book.get('hero')
            book.bpub_date = updata_book.get('time')
            book.bread = updata_book.get('read')
            book.bcomment = updata_book.get('comment')

            book.save()
            return http.JsonResponse({'data':'修改成功'})
        except Exception as e:
            print(e)
            return http.JsonResponse({'data':'修改失败'})
